package cn.dansj.handler.tasks;

import cn.dansj.annotation.MarkAsTask;
import cn.dansj.common.utils.file.FileUtils;
import cn.dansj.utils.minio.MinioUtils;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.utils.project.ProjectUtils;
import com.xxl.job.handler.Job;

import java.net.ConnectException;
import java.util.regex.Matcher;

@SuppressWarnings("all")
@MarkAsTask
public class DataxPluginHandler extends Job {
    public final String minioBucketName = "plugin";
    public final String minioMenuName = "datax";
    public final boolean dispenseIfNotExists = true;

    @Override
    public void execute() {
        try {
            MinioUtils minioUtils = ProjectUtils.getMinio();
            boolean folderExist = minioUtils.isDir(minioBucketName, minioMenuName);
            if (folderExist) {
                logger.info("minio中datax插件存在");
                String userHome = System.getProperty("user.home");
                boolean exists = FileUtils.exists(userHome + "/plugin/datax");
                logger.info("本地datax插件" + (exists ? "已存在" : "不存在"));
                if (!exists && dispenseIfNotExists) {
                    String message = minioUtils.download(minioBucketName, minioMenuName, userHome + "/plugin").toJSONString().replaceAll("[/\\\\]", Matcher.quoteReplacement(System.getProperty("file.separator")))
                            .replaceAll("[/\\\\]+", Matcher.quoteReplacement(System.getProperty("file.separator")));
                    logger.info(message);
                }
            } else {
                logger.info("minio中datax插件不存在,请手动上传");
            }
        } catch (Exception exception) {
            Class<? extends Throwable> baseClass = Transformation.getBaseException(exception).getClass();
            if (baseClass.equals(ConnectException.class)) {
                logger.error("minio连接失败,请检查配置是否正确");
            }
            logger.error(exception);
        }
    }
}
